package com.rt.easyjava.base.modules.timerjob.service.job.jobStrategy;

import com.rt.easyjava.base.modules.timerjob.dto.TmptTimerBizDto;
import com.rt.easyjava.base.modules.timerjob.service.job.jobStrategy.strategy.HttpRemoteJobStrategy;
import com.rt.easyjava.base.modules.timerjob.service.job.jobStrategy.strategy.ProcedureJobStrategy;
import com.rt.easyjava.base.modules.timerjob.service.job.jobStrategy.strategy.StringBeanJobStrategy;
import com.rt.easyjava.common.base.Result;

import java.util.HashMap;
import java.util.Map;

/**
 * 策略工厂，使用到设计模式：简单工厂、策略、模板
 */
public class JobStrategyFactory {
    public static JobStrategy getJobStrategy(TmptTimerBizDto tmptTimerBizDto) {
        String className = tmptTimerBizDto.getClassName();
        Result typeResult = isClassInstance(className);
        String type = (String) typeResult.getMap().get("type");

        JobStrategy jobStrategy = null;
        if (type.equalsIgnoreCase("1")) {
            jobStrategy = new ProcedureJobStrategy(tmptTimerBizDto, typeResult);
        }
        else if (type.equalsIgnoreCase("2")) { // spring 方法
            jobStrategy = new StringBeanJobStrategy(tmptTimerBizDto, typeResult);
        }
        // remote invoke
        else if (type.equalsIgnoreCase("3")) {
            jobStrategy = new HttpRemoteJobStrategy(tmptTimerBizDto, typeResult);
        }

        return jobStrategy;
    }



    /**
     * className 有以下三种情况，通过分析字符串来判断是哪种情况:
     * 1, com.rt.ej.quart.job.MyJobBean
     * 2, quartzService.test()
     * 3, http://resource-base/coding/test
     * @param className
     * @return
     */
    private static Result isClassInstance(String className) {
        // quartzService.test()
        className = className.trim();
        if (className.startsWith("call ")) {
            String procName = className.substring(className.indexOf(" ")+1);
            if (procName.contains("(")) {
                procName = procName.substring(0, procName.indexOf('('));
            }
            System.out.println("procName:"+procName);
            Map<String, String> map = new HashMap<>();
            map.put("procName",procName);
            map.put("type","1");
            return Result.builder(map);
        }
        else if (className.endsWith("()")) {
            String classInstance = className.substring(0, className.indexOf('.'));
            String classMethod = className.substring(className.indexOf('.')+1, className.indexOf('('));
            Map<String, String> map = new HashMap<>();
            map.put("classInstance",classInstance);
            map.put("classMethod",classMethod);
            map.put("type","2");
            return Result.builder(map);
        }
        // http://resource-base/coding/test
        else {
            Map<String, String> map = new HashMap<>();
            map.put("type","3");
            return Result.builder(map);
        }

    }

}
